
package com.scs.application.modules.base.controller;


import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.scs.application.core.exceptions.ExportException;
import com.scs.application.core.exceptions.ImportException;
import com.scs.application.core.model.*;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.mvc.controller.ImAndExAbleController;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.core.utils.PoiUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.excel.ExportExcel;
import com.scs.application.modules.base.dto.ExcelMaterialCatalogDTO;
import com.scs.application.modules.base.entity.MaterialCatalog;
import com.scs.application.modules.base.request.MaterialCatalogQueryRequest;
import com.scs.application.modules.base.service.MaterialCatalogService;
import com.scs.application.modules.base.vo.MaterialCatalogVO;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * 商品品类 controller
 */
@AllArgsConstructor
@RestController
@RequestMapping("/base/material_catalogs")
public class MaterialCatalogController extends CrudController<MaterialCatalog, String, MaterialCatalogService> implements ImAndExAbleController<MaterialCatalogQueryRequest> {

    @GetMapping("/page")
    public PageResult page(MaterialCatalogQueryRequest request) {
        IPage page = service.page(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    @GetMapping("/page_for_supplier")
    public PageResult pageForSupplier(MaterialCatalogQueryRequest request) {
        IPage page = service.pageForSupplier(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    @GetMapping("/list")
    public CommonResult list(MaterialCatalogQueryRequest request) {
        List<MaterialCatalog> list = service.list(request);
        return CommonResult.ok("查询成功", list);
    }

    @GetMapping("/tree")
    public CommonResult tree(MaterialCatalogQueryRequest request) {
        List<MaterialCatalog> list = service.list(request);

        TreeNode root = null;
        if (request.isAutoAddRoot()) {
            root = new TreeNode();
            root.setId("0");
            root.setTitle("商品分类");
        }

        TreeModel<MaterialCatalog> treeModel = new TreeModel<MaterialCatalog>(list, "name", root) {
            @Override
            protected void addExtraProperties(TreeNode node, MaterialCatalog entity) {
                node.addProperty("materialTypeCode", entity.getMaterialTypeCode());
                node.addProperty("code", entity.getCode());
            }
        };
        return CommonResult.ok("查询成功", treeModel.asList());
    }

    @GetMapping("/tree_for_supplier")
    public CommonResult treeForSupplier(MaterialCatalogQueryRequest request) {
        List<MaterialCatalog> list = service.listForSupplier(request);

        TreeNode root = null;
        if (request.isAutoAddRoot()) {
            root = new TreeNode();
            root.setId("0");
            root.setTitle("商品分类");
        }

        TreeModel<MaterialCatalog> treeModel = new TreeModel<MaterialCatalog>(list, "name", root) {
            @Override
            protected void addExtraProperties(TreeNode node, MaterialCatalog entity) {
                /*node.addProperty("materialTypeCode", entity.getMaterialTypeCode());
                node.addProperty("code", entity.getCode());*/
            }
        };
        return CommonResult.ok("查询成功", treeModel.asList());
    }


    @Override
    @DeleteMapping("/{id}")
    public CommonResult deleteById(@PathVariable("id") String id) {
        boolean bRemove = service.deleteById(id);
        return bRemove ? CommonResult.ok("删除成功") : CommonResult.error("删除失败");
    }

    @Override
    public void excelExport(MaterialCatalogQueryRequest request) {
        String fileName = "商品品类信息" + DateUtils.format(DateUtils.now(), "yyyyMMddHHmmss") + ".xlsx";
        List<MaterialCatalogVO> list = this.service.exportList(request);
        try {
            (new ExportExcel("商品品类信息", MaterialCatalogVO.class)).setDataList(list).write(this.response(), fileName).dispose();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /* @Override
     public CommonResult<ImportResult> excelImport(MultipartFile file) throws ImportException {
         return CommonResult.ok("导入成功",this.service.excelImport(file));
     }*/
    @Override
    public CommonResult<ImportResult> excelImport(MultipartFile file) throws ImportException {
        return CommonResult.ok("导入成功", service.excelImport(file));
    }

    /**
     * 品类导出数据模板
     */
    @Override
    public void excelTemplate(MaterialCatalogQueryRequest request) {
        String fileName = "1商品品类导入.xlsx";
        ExportParams params = PoiUtils.getDefaultExportParams("商品品类导入模板", "商品品类信息", true);
        params.setExclusions(new String[]{"错误行号", "错误信息"});
        ExcelMaterialCatalogDTO mockData = PoiUtils.mockData(ExcelMaterialCatalogDTO.class);
        try {
            setDownloadParam(fileName);
            PoiUtils.exportExcel(response().getOutputStream(), params, ExcelMaterialCatalogDTO.class, Lists.newArrayList(mockData));
        } catch (IOException e) {
            throw new ExportException("导出异常", e);
        }
    }

  /*  @Override
    public void excelTemplate(MaterialCatalogQueryRequest request) {
        try {
            String fileName = "商品品类导入模板.xlsx";

            MaterialCatalogDTO mockData = PoiUtils.mockData(MaterialCatalogDTO.class);

            new ExportExcel("商品品类信息", MaterialCatalogDTO.class, 2)
                    .setDataList(Lists.newArrayList(mockData)).write(response(), fileName).dispose();
        } catch (Exception e) {
            throw new BusinessException("导出模板失败", e);
        }
    }*/


    /***
     * @Description:  通用删除，多个
     */
    @DeleteMapping("/deleteBatchCommon")
    public RestResult deleteBatchCommon(@RequestBody Map<String, Object> para) {
        List<Serializable> ids = (List<Serializable>) para.get("ids");
        Boolean isOk = service.removeCascadeBatchByIds(ids);
        if (!isOk) {
            return RestResult.error("数据删除失败<br>可能所操作数据已被删除，请刷新页面重新尝试操作");
        }
        return RestResult.ok("数据删除成功");
    }

    /***
     * @param id
     * @Description:  通用查找，单个
     */
    @GetMapping("/findByIdCommon")
    public RestResult findByIdCommon(@RequestParam("id") Serializable id) {
        MaterialCatalog entity = service.getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        if (StringUtils.isNotBlank(entity.getParentId()) && !"0".equals(entity.getParentId())) {
            MaterialCatalog entityParent = service.getById(entity.getParentId());
            if (entityParent != null) {
                entity.setParentCode(entityParent.getCode()).setParentName(entityParent.getName()).setParentId(entityParent.getId());
            }
        } else{
            entity.setParentName("商品分类").setParentId("0");
        }

        return RestResult.ok("获取数据成功", entity);
    }
}
